/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.fee.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.PrimaryGenerater;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.mapper.JsonMapper;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.fee.entity.*;
import com.jeeplus.modules.fee.entity.vo.InvoicePayRecord;
import com.jeeplus.modules.fee.service.*;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 应付结算单Controller
 * @author weisong
 * @version 2017-09-18
 */
@Controller
@RequestMapping(value = "${adminPath}/fee/payable")
public class PayableController extends BaseController {

	@Autowired
	private PayableService payableService;
	@Autowired
	private ConsignorService consignorService;
	@Autowired
	private PayTipService payTipService;
	@Autowired
	private PayInvoiceService payInvoiceService;
	@Autowired
	private PayableDetailService payableDetailService;
	@Autowired
	private DetailService detailService;
	@Autowired
	private PaymentDetailService paymentDetailService;
	@Autowired
	private PayInvoiceDetailService payInvoiceDetailService;
	@Autowired
	private ReceivablesService receivablesService;

	@ModelAttribute
	public Payable get(@RequestParam(required=false) String id) {
		Payable entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = payableService.get(id);
		}
		if (entity == null){
			entity = new Payable();
		}
		return entity;
	}

	/**
	 * 应付结算单列表页面
	 */
	@RequiresPermissions("fee:payable:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/fee/payableList";
	}
	
		/**
	 * 应付结算单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("fee:payable:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Payable payable, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Payable> page = payableService.findPage(new Page<Payable>(request, response), payable); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑应付结算单表单页面
	 */
	@RequiresPermissions(value={"fee:payable:view","fee:payable:add","fee:payable:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Payable payable, Model model) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		model.addAttribute("payable", payable);
		if(StringUtils.isBlank(payable.getId())){//如果ID是空为添加
			model.addAttribute("isAdd", true);
		}
		//供结算方下拉框使用
        Consignor cc = new Consignor();
        List<Consignor> consignors = consignorService.findList(cc);
        model.addAttribute("consignors", consignors);
		//当应付账款不为空时调用收票付款记录的方法
		if (null != payable) {
			InvoicePayRecord(payable.getId(), model);
		}
		//设置结算单关联的订单（数据源页面直接选择订单生成结算单，没有经过明细）
		PayTip feePayTip = new PayTip();
		feePayTip.setFeePayable(payable);
		List<PayTip> tips = payTipService.findList(feePayTip);//获得结算单关联的所有订单行号
		if (null != tips && tips.size() > 0) {
			for (int i = 0; i < tips.size(); i++) {
				feePayTip = tips.get(i);
				Integer row = feePayTip.getRowNo();
				if (row == null || row < 0) continue;

			}
		}
		//点击少收补票按钮后将原结算单信息带入新增的结算单
		String payableId = request.getParameter("payableId");
		if (StringUtils.isNotEmpty(payableId)) {
			model.addAttribute("payableId", payableId);
			Payable payable1 = payableService.get(payableId);
			if (null != payable) {
				//设置结算方
				payable.setPayee(payable1.getPayee());
				//设置结算单号
				payable.setClearingNo(payable1.getClearingNo());
			}
		}
		String receId = request.getParameter("receId");
		String typeSign = request.getParameter("typeSign");
		//点击应收结算单的多收冲账按钮后将原结算单信息带入新增的应付结算单
		if (StringUtils.isNotEmpty(receId)) {
			model.addAttribute("receId", receId);
			model.addAttribute("typeSign", typeSign);
			Receivables rece = receivablesService.get(receId);
			if (null != rece) {
				//设置结算方
				payable.setPayee(rece.getPayerName());
				//设置结算单号
				payable.setClearingNo(rece.getClearingNo());
			}
		}
		//查询应付账款明细与应付账款相关联的数据
		PayableDetail payableDetail = new PayableDetail();
		Payable able = payableService.get(payable.getId());
		if (able != null) {
			payableDetail.setFeePayable(able);
			List<PayableDetail> list = payableDetailService.findList(payableDetail);
			if (null != list && list.size() > 0) {
				model.addAttribute("list", list);
				model.addAttribute("flag", "payable");
			}
		}
		String different = request.getParameter("different");
		if (null != different && different != "") {
			model.addAttribute("different", different);
		}
		return "modules/fee/payableForm";
	}

	/**
	 * 保存应付结算单
	 */
	@RequiresPermissions(value={"fee:payable:add","fee:payable:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(Payable payable, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, payable)){
			return form(payable, model);
		}
		//新增或编辑表单保存
		//获取原应付结算单id【应付的少收补票】
		String payableId = request.getParameter("payableId");
		//获取原应收结算单id【应收的多收冲账】
		String receId = request.getParameter("receId");
		//获取结算金额
		String cm = request.getParameter("clearingMoney");
		Double settlement = StringUtils.isEmpty(cm) ? 0.00 : Double.parseDouble(cm);
		//获取备注
		String comment = request.getParameter("remarks");
		if (StringUtils.isNotEmpty(receId)) {
			if (null != settlement && StringUtils.isNotEmpty(comment)) {
				//调用保存点击应收结算单的多收冲账按钮之后新增的应付结算单
				saveCorrectionFeeReceivables(receId, payable, settlement, comment);
				addMessage(redirectAttributes, "保存应收结算单成功");
				return "redirect:" + Global.getAdminPath() + "/fee/receivables/?repage";
			}
		} else if (StringUtils.isNotEmpty(payableId)) {
			if (null != settlement && StringUtils.isNotEmpty(comment)) {
				//调用保存点击应付结算单的少收补票按钮之后新增的结算单
				saveCorrectionPayable(payableId, payable, settlement, comment);
				addMessage(redirectAttributes, "保存应付结算单成功");
			}
		}else{
			//生成单号
			String number = "";
			Payable payble = payableService.findClearingNoBusyDate();
			Format format1 = new SimpleDateFormat("yyyyMMdd");    //初始化时间格式
			//比较结算日期是否和现在的日期相等
			if (null == payble) {
				number = PrimaryGenerater.getInstance().generaterNextNumber("YFJS", null);
			} else {
				if (String.valueOf(format1.format(payble.getBusyDate())).equals(String.valueOf(format1.format(new Date())))) {
					number = PrimaryGenerater.getInstance().generaterNextNumber("YFJS", payble.getClearingNo());
				} else {
					number = PrimaryGenerater.getInstance().generaterNextNumber("YFJS", null);
				}
			}
			//获取结算金额
			String clearMoney = request.getParameter("clearingMoney");
			Double clear = StringUtils.isEmpty(clearMoney) ? 0.00 : Double.parseDouble(clearMoney);
			payable.setClearingNo(number);
			if (clear != null) {
				payable.setClearingMoney(clear);
			}
			payableService.save(payable);//保存
			String ids = request.getParameter("ids") == null ? "" : request.getParameter("ids");
			if(StringUtils.isNotEmpty(ids)){
				savePayableDetail(ids,payable);
			}
			addMessage(redirectAttributes, "保存应付结算单成功");
		}
		return "redirect:"+Global.getAdminPath()+"/fee/payable/?repage";
	}
	
	/**
	 * 删除应付结算单
	 */
	@ResponseBody
	@RequiresPermissions("fee:payable:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Payable payable, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		payableService.delete(payable);
		j.setMsg("删除应付结算单成功");
		return j;
	}
	
	/**
	 * 批量删除应付结算单
	 */
	@ResponseBody
	@RequiresPermissions("fee:payable:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			//根据应付结算单id查询应付结算单明细表
			PayableDetail feePayableDetail = new PayableDetail();
			feePayableDetail.setFeePayable(payableService.get(id));
			List<PayableDetail> list = payableDetailService.findList(feePayableDetail);
			for (int i = 0; i < list.size(); i++) {
				//System.out.println(list.get(i).getFeeDetail().getId());
				//获取应付结算单明细表中的费用明细表的id。修改费用明细表的状态
				detailService.updateStatusById(Detail.updateStatus1, list.get(i).getFeeDetail().getId());
				//删除应付结算单明细表
				payableDetailService.delete(list.get(i));
			}
			payableService.delete(payableService.get(id));
		}
		j.setMsg("删除应付结算单成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("fee:payable:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Payable payable, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "应付结算单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Payable> page = payableService.findPage(new Page<Payable>(request, response, -1), payable);
    		new ExportExcel("应付结算单", Payable.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出应付结算单记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("fee:payable:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Payable> list = ei.getDataList(Payable.class);
			for (Payable payable : list){
				try{
					payableService.save(payable);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条应付结算单记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条应付结算单记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入应付结算单失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/payable/?repage";
    }
	
	/**
	 * 下载导入应付结算单数据模板
	 */
	@RequiresPermissions("fee:payable:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "应付结算单数据导入模板.xlsx";
    		List<Payable> list = Lists.newArrayList(); 
    		new ExportExcel("应付结算单数据", Payable.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/payable/?repage";
    }

	/**
	 * 查询收票付款记录
	 *
	 * @param id 应付结算单id
	 */
	public void InvoicePayRecord(String id, Model model) {
		if (StringUtils.isNotEmpty(id)) {
			List<InvoicePayRecord> iprList = new ArrayList<InvoicePayRecord>();
			InvoicePayRecord ipr = null;
			//获取发票记录
			List<PayInvoice> payInvoices = payInvoiceService.findPayInvoiceByInvoiceDetail(id);
			//合计（一张结算单的总开票金额和总核销金额）
			double totalInvoice = 0;
			double totalVcamoney = 0;
			for (PayInvoice fpi : payInvoices) {
				//new一个VO类[用来封装收票付款记录]
				ipr = new InvoicePayRecord();
				ipr.setInvoiceId(fpi.getId());    //发票id
				ipr.setInvoiceNo(fpi.getInvoiceNo());    //发票号
				ipr.setInvoiceDate(fpi.getInvoiceDate());    //开票时间
				ipr.setInvoiceTotalMoney(fpi.getInvoiceMoney());    //发票总金额
				ipr.setVcaTotalMoney(fpi.getVcaMoney());    //核销总金额
				//根据结算单id和发票主表id获取发票子表
				System.out.println(fpi.getId());
				PayInvoiceDetail invoiceDetail = payInvoiceDetailService.findAllByPayableId(id, fpi.getId());
				//设置本次开票金额
				ipr.setInvMoney(invoiceDetail.getInvMoney());
				//计算合计的开票金额
				totalInvoice += invoiceDetail.getInvMoney();
				//获取付款单子表
				List<PaymentDetail> paymentDetails = paymentDetailService.findPaymentDetailByInvoiceId(fpi.getId(), invoiceDetail.getId());
				double theVcaMoney = 0;
				for (PaymentDetail fpd : paymentDetails) {
					theVcaMoney += fpd.getTheVcaMoney();
				}
				//设置本次核销金额
				ipr.setTheVcaMoney(theVcaMoney);
				//计算合计的核销金额
				totalVcamoney += theVcaMoney;
				//设置付款单子表
				ipr.setPaymentDetails(paymentDetails);
				//将对象添加到iprList
				iprList.add(ipr);
			}
			model.addAttribute("iprList", iprList);
			model.addAttribute("totalInvoice", totalInvoice);
			model.addAttribute("totalVcamoney", totalVcamoney);
		}
	}
	/**
	 * 获取弹出窗口的数据
	 */
	@RequestMapping(value="findAllDetail")
	public @ResponseBody String findAllDetail(Detail feeDetail, HttpServletRequest request, HttpServletResponse response){
		// 判断引入明细的状态是否为未结算
		String _status = request.getParameter("status");
		//获取查询框输入的值
		String startDate = request.getParameter("startTime");
		String endDate = request.getParameter("endTime");
		//获取结算方
		String clearId = request.getParameter("balance");
		//判断状态不为空
		if (StringUtils.isNotEmpty(_status)) {
			Integer status = Integer.parseInt(_status);
			feeDetail.setStatus(status);
		}
		//判断结算方不为空
		if (StringUtils.isNotEmpty(clearId)) {
			Consignor f = new Consignor();
			f.setId(clearId);
			feeDetail.setClearUnit(f);
		}
		//判断查询时间是否为空
		if(null != startDate && startDate != "" && null != endDate && endDate != ""){
			//String转化为Date
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date start = null;//开始时间
			Date end = null;//结束时间
			try {
				start = sdf.parse(startDate+" 00:00:00");//开始时间
				end = sdf.parse(endDate+" 23:59:59");//结束时间
			} catch (ParseException e) {
				e.printStackTrace();
			}
			feeDetail.setStartDate(start);
			feeDetail.setEndDate(end);
		}
		//feeType:0是收入  1是支出
		String _feeType = request.getParameter("feeType");
		if(StringUtils.isNotEmpty(_feeType)){
			Type feeType = new Type();
			feeType.setFeeType(Integer.parseInt(_feeType));
			feeDetail.setFeeType(feeType);
		}
		List<Detail> list  = detailService.findList(feeDetail);
		String result = JsonMapper.toJsonString(list);
		return result;
	}

	/**
	 * 跳转到新增应付账款页面
	 */
	@RequestMapping(value = "addPayable")
	public @ResponseBody String addPayable(@RequestParam String ids) {
		// 如果ids为空，则跳转到detailForm
		String url = "/fee/detail/?repage";
		List<Detail> list = new ArrayList<Detail>();
		if (StringUtils.isNotEmpty(ids)) { // 判断ids是否为空
			String[] _ids = ids.split(",");
			for (String id : _ids) {
				if (StringUtils.isNotEmpty(id)) {
					Detail feeDetail = detailService.get(id);
					list.add(feeDetail);
				}
			}
		}
		return JsonMapper.toJsonString(list);
	}

	/**
	 * 当点击已确认按钮时修改状态
	 */
	@RequestMapping(value = "updateStatus")
	public @ResponseBody AjaxJson updateStatus(String ids,HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		//String ids = request.getParameter("ids");
		String idArray[] =ids.split(",");
		for(String id : idArray){
			payableService.updateMoneyAndStatusById(Payable.updateStatus3, null, null, null, null, id);
		}
		j.setMsg("应付结算单状态修改成功");
		return j;
	}
	/**
	 * 当点击已确认按钮时修改状态
	 */
	@RequestMapping(value = "updateStatusTwo")
	public String updateStatusTwo(String id) {
		payableService.updateMoneyAndStatusById(Payable.updateStatus3, null, null, null, null, id);
		return "redirect:" + Global.getAdminPath() + "/fee/payable/form?id=" + id;
	}

	/**
	 * 删除应付结算单明细并修改费用明细表的状态
	 * @param id 应付结算单子表id
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "removePayableDetail")
	public String removePayableDetail(String id, RedirectAttributes redirectAttributes) {
		//根据id查询应付结算单子表
		PayableDetail feePayableDetail = payableDetailService.get(id);
		//根据费用明细id更新状态【已结算修改为未结算】
		detailService.updateStatusById(Detail.updateStatus1, feePayableDetail.getFeeDetail().getId());
		//获取结算单子表的计费金额
		Double detailMoney = feePayableDetail.getClearingMoney()==null?feePayableDetail.getPayMoney():feePayableDetail.getClearingMoney();
		//获取应付结算单主表
		Payable feePayable = payableService.get(feePayableDetail.getFeePayable());
		//获取应付结算单主表的结算金额
		Double clearMoney = feePayable.getClearingMoney();
		//更新应付结算单主表的结算金额
		if ( null != clearMoney && null != detailMoney) {
			feePayable.setClearingMoney((clearMoney-detailMoney));
			payableService.save(feePayable);
		}
		payableDetailService.delete(feePayableDetail);
		addMessage(redirectAttributes, "删除应付账款明细成功");
		return "redirect:"+Global.getAdminPath()+"/fee/payable/form?id="+feePayable.getId();
	}

	/**
	 * 开票操作（跳转到新增发票页面）
	 */
	@RequestMapping(value = "invoiceOperation")
	public String invoiceOperation(@RequestParam String ids, @RequestParam Integer type, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		//如果ids为空，则跳转到payableForm
		String url = "/fee/payable/?repage";
		if (StringUtils.isNotEmpty(ids)) {    //判断ids是否为空
			String[] _ids = ids.split(",");
			List<Payable> list = new ArrayList<Payable>();
			for (String id : _ids) {
				if (StringUtils.isNotEmpty(id)) {
					Payable payble = payableService.get(id);
					list.add(payble);
				}
			}
			redirectAttributes.addFlashAttribute("list", list);
			redirectAttributes.addFlashAttribute("flag", "payable");
			redirectAttributes.addFlashAttribute("ids", ids);
			redirectAttributes.addFlashAttribute("type", type);
			String target = request.getParameter("target") == null ? "payableList" : "invoiceList";
			url = "/fee/payInvoice/form?target=" + target;
		}
		return "redirect:" + Global.getAdminPath() + url;
	}

	/**
	 * 点击关闭按钮时更新结算单状态和关闭原因
	 */
	@RequestMapping(value = "closePayable")
	public @ResponseBody
	int closePayable(HttpServletRequest request) {
		//获取结算单id
		String ableId = request.getParameter("id");
		//获取关闭原因
		String closeReasn = request.getParameter("closeReason");
		int i = 1;
		//根据id获取结算单
		if (StringUtils.isNotEmpty(ableId)) {
			Payable feePayable = payableService.get(ableId);
			//修改状态为已关闭
			feePayable.setStatus(Payable.CLOSED);
			if (StringUtils.isNotEmpty(closeReasn)) {
				feePayable.setCloseReason(closeReasn);
			}
			payableService.save(feePayable);
		}
		return i;
	}

	/**
	 * 保存应付结算单明细表
	 */
	public void savePayableDetail(String temp_ids,Payable payable){
		// 保存应付账款明细
		// 获取费用明细表的id并保存
		PayableDetail fpd = null;
		String[] _ids = temp_ids.split(","); //
		// 将form页面取的id值循环遍历
		if (_ids.length != 0) {
			for (String id : _ids) {
				if (StringUtils.isNotEmpty(id)) {
					fpd = new PayableDetail();
					Detail feeDetail = detailService.get(id);
					fpd.setFeeDetail(feeDetail);
					fpd.setBusyDate(feeDetail.getBusyDate());
					fpd.setFeeAgreement(feeDetail.getFeeAgreement());
					fpd.setFeeType(feeDetail.getFeeType());
					fpd.setPayMoney(feeDetail.getPayMoney());
					fpd.setClearingMoney(feeDetail.getClearingMoney());
					fpd.setFeePayable(payable);
					payableDetailService.save(fpd);
					// 修改计费费用明细表的状态
					detailService.updateStatusById(Detail.updateStatus, id);
				}
			}
		}
	}

	/**
	 * 保存点击应收结算单多收冲账按钮之后的应付结算单
	 *
	 * @param receId     原应收结算单id
	 * @param feePayable
	 * @param payMoney   结算金额
	 * @param comment    备注
	 */
	public void saveCorrectionFeeReceivables(String receId, Payable feePayable, Double payMoney, String comment) {
		Receivables receivables = receivablesService.get(receId);
		if (null != receivables) {
			//设置结算方
			feePayable.setPayee(receivables.getPayerName());
			//设置结算单号
			feePayable.setClearingNo(receivables.getClearingNo());
			//设置结算金额
			feePayable.setClearingMoney(payMoney);
			//设置备注
			feePayable.setRemarks(comment);
			payableService.save(feePayable);
		}
	}

	/**
	 * 保存点击应付结算单少收补票按钮之后的应付结算单
	 *
	 * @param payableId  原结算单id
	 * @param feePayable
	 * @param clearMoney 结算金额
	 * @param comment    备注
	 */
	public void saveCorrectionPayable(String payableId, Payable feePayable, Double clearMoney, String comment) {
		Payable payable = payableService.get(payableId);
		if (null != payable) {
			//设置结算方
			feePayable.setPayee(payable.getPayee());
			//设置结算单号
			feePayable.setClearingNo(payable.getClearingNo());
			//设置结算金额
			feePayable.setClearingMoney(clearMoney);
			//设置备注
			feePayable.setRemarks(comment);
			payableService.save(feePayable);
		}
	}

	/**
	 * 计费明细页面结算按钮生成结算单
	 * ,,
	 */
	@RequiresPermissions(value = {"fee:payable:add", "fee:payable:edit"}, logical = Logical.OR)
	@RequestMapping(value = "balanceSave")
	public @ResponseBody
	String balanceSave(@RequestParam(value = "ids") String ids, @RequestParam(value = "clearUnit") String clearUnit,
					   @RequestParam(value = "clearMon") String money, @RequestParam(value = "remark") String remark) {
		if (StringUtils.isNotEmpty(ids) && StringUtils.isNotEmpty(clearUnit) && StringUtils.isNotEmpty(money)) {
			Payable feePayable = new Payable();
			feePayable.setStatus(0);
			//生成单号
			String maxNumber = "";
			Payable payble = payableService.findClearingNoBusyDate();
			Format format1 = new SimpleDateFormat("yyyyMMdd");    //初始化时间格式
			//比较结算日期是否和现在的日期相等
			if (null == payble) {
				maxNumber = PrimaryGenerater.getInstance().generaterNextNumber("YFJS", null);
			} else {
				if (String.valueOf(format1.format(payble.getBusyDate())).equals(String.valueOf(format1.format(new Date())))) {
					maxNumber = PrimaryGenerater.getInstance().generaterNextNumber("YFJS", payble.getClearingNo());
				} else {
					maxNumber = PrimaryGenerater.getInstance().generaterNextNumber("YFJS", null);
				}
			}
			feePayable.setClearingNo(maxNumber);
			feePayable.setBusyDate(new Date());
			feePayable.setClearingMoney(Double.parseDouble(money));
			Consignor payee = consignorService.findByName(clearUnit);
			feePayable.setPayee(payee);
			feePayable.setRemarks(StringUtils.isEmpty(remark) ? "" : remark);
			payableService.save(feePayable);

			//开始保存子表
			savePayableDetail(ids,feePayable);
			return "0";
		} else {
			return "1";
		}
	}

	/**
	 * 引入明细时的确定按钮
	 */
	@RequestMapping(value = "addInvoice")
	public
	@ResponseBody
	String addInvoice(@RequestParam String ids, Model model, RedirectAttributes redirectAttributes) {
		//如果ids为空，则跳转到feeReceivablesForm
		String url = "/fee/payable/?repage";
		List<Payable> list = new ArrayList<Payable>();
		if (StringUtils.isNotEmpty(ids)) {    //判断ids是否为空
			String[] _ids = ids.split(",");
			for (String id : _ids) {
				if (StringUtils.isNotEmpty(id)) {
					Payable payble = payableService.get(id);
					list.add(payble);
				}
			}
		}
		return JsonMapper.toJsonString(list);
	}

	/**
	 * 当点击明细表删除一条查询出来的记录
	 * id 选中删除的明细id，str所有的id
	 */
	@RequestMapping(value = "remove")
	public
	@ResponseBody
	String remove(String id, String str, Model model, RedirectAttributes redirectAttributes) {
		String ids = "";
		List<Payable> list = new ArrayList<Payable>();
		if (str != null && id != null) {
			String[] _ids = str.split(",");
			for (String ableId : _ids) {
				if (StringUtils.isNotEmpty(ableId)) {
					if (!ableId.equals(id)) {
						ids += ableId + ",";
						Payable feePayable = payableService.get(ableId);
						list.add(feePayable);
					}
				}
			}
		}
		return JsonMapper.toJsonString(list);
	}


}